package com.itheima.leadnews.admin.filter;

import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class AuthorizationFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String uri = request.getURI().getPath();
        //判断是否访问登录接口
        if (uri.contains("/login/in")) {
            //放行
            return chain.filter(exchange);
        }
        //不是,判断是否携带token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            //没有携带token,响应401状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //携带token,校验token合法性
        try {
            //不抛异常,token合法,放行
            Claims claims = AppJwtUtil.getClaimsBody(token);
            return chain.filter(exchange);
        } catch (Exception e) {
            //抛异常,token不合法
            //没有携带token,响应401状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            e.printStackTrace();
            return response.setComplete();
        }
    }
}
